﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace SimpleBlog.Mvc
{
    public class SummaryRequiredAttribute : ValidationAttribute, IClientValidatable
    {
        private string _summarySeparator;

        public SummaryRequiredAttribute(string summarySeparator, string errorMessage)
            : base(errorMessage)
        {
            _summarySeparator = summarySeparator;
        }

        public SummaryRequiredAttribute(string summarySeparator, Func<string> errorMessageAccessor)
            : base(errorMessageAccessor)
        {
            _summarySeparator = summarySeparator;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRegexRule(
                ErrorMessageString, string.Format("[\\s\\S]*{0}[\\s\\S]*", _summarySeparator));
        }

        public override bool IsValid(object value)
        {
            if (value is string
                && value.ToString().Contains(_summarySeparator))
                return true;

            return false;
        }
    }
}